<template>
    <div class="address">
        <van-nav-bar
      fixed
      title="收货地址"
      left-arrow
      right-text='管理'
      @click-left="$router.go(-1)"
      @click-right="becomedelete"
      class="nav"
    />
    <van-address-list v-if="!isManageMode"
      v-model="defaultId"
      :list="computedList"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      add-button-text='新增地址'
    >
     </van-address-list>
     <van-address-list v-else
      v-model="deleteId"
      :list="computedList"
      @add="onAdd"
      @edit="onEdit"
      add-button-text='删除地址'
    >
     </van-address-list>
    </div>
</template>
<script>
import { getAddressList, getAddressDefaultId, setDefault, removeAddress } from '@/api/address'

export default {
  name: 'addressList',
  data () {
    return {

      beforeList: [],
      defaultId: '',
      list: [],
      isManageMode: false, // 是否处于管理模式的标志
      deleteId: ''
    }
  },
  methods: {
    async onAdd (item) {
    //   Toast('新增地址')
      if (!this.isManageMode) {
        this.$router.push({
          path: '/addressedit',
          query: {
            form: {
              name: '',
              tel: ''
            }
          }
        })
      } else {
        // console.log(this.deleteId)
        await removeAddress(this.deleteId)
        this.getbeforelist()
      }
    },
    onDelete () {

    },
    onEdit (item) {
      // Toast('编辑地址:' + item)
      console.log(item)
      this.$router.push({
        path: '/addressedit',
        query: {
          form: {
            name: item.name,
            tel: item.tel,
            id: item.id
          }
        }
      })
    },
    async getbeforelist () {
      const { data: { list } } = await getAddressList()
      console.log(list)
      this.beforeList = list
    },
    getLongadd (item) {
      return item.region.province + item.region.city + item.region.region + item.detail
    },
    async getdefaultId (id) {
      const { data: { defaultId } } = await getAddressDefaultId()
      // console.log(defaultId)
      this.defaultId = defaultId
    },
    isDefault (id) {
      if (id === this.defaultId) {
        return true
      }
      return false
    },
    becomedelete () {
      this.isManageMode = !this.isManageMode
    }
  },
  computed: {
    computedList () {
      return this.beforeList.map(item => ({
        id: item.address_id,
        name: item.name,
        tel: item.phone,
        address: this.getLongadd(item),
        isDefault: this.isDefault(item.address_id)
      }))
    }
  },
  created () {
    this.getbeforelist()
    this.getdefaultId()
  },
  watch: {
    async defaultId (newVal) {
      await setDefault(newVal)
    //  console.log(newVal)
    }
  }
}
</script>
<style lang="less" scoped>
.van-nav-bar__text {
    color: #333;
}
.address {
    padding-top: 46px;
    padding-bottom: 46px;

  }
  .van-address-item {
   border: solid 2px pink;
}
</style>
